import {defineStore} from 'pinia'
import interaction from "@/util/Interaction";

export const baseStore = defineStore('baseStore', {
    state: () => {
        return {
            localState: null,
            menuFoldState: true,
            fullscreenState: false,
            menuTab: [],
            token: null,
            update: false,
            expired: false,
            // menuState 必须为{ menu:[],button:[] }对象，其中menu为菜单，button为按钮
            menuState: {
                menu:[],
                button:[]
            }
        }
    },
    getters: {
        getLocalState() {
            return this.localState
        }
    },
    actions: {
        /**
         * 两个不为tree结构的路由,会返回一个带tree的路由
         * @param rearRouter 后端维护的权限集合
         * @param frontRouter 前端维护的路由集合
         */
        async formatRouter(rearRouter, frontRouter) {
            this.menuState = {
                menu:[],
                button:[]
            }
            try {
                let button = []
                if (rearRouter == null || rearRouter.length < 1) {
                    this.menuState = {
                        menu:frontRouter,
                        button:button
                    }
                    return
                }
                let menu = await interaction.treeToFlat(frontRouter, 'children')
                let list = await rearRouter.map(rear => {
                    delete rear.children
                    let front = menu.find(front => front.path === rear.path)
                    if (front) {
                        rear = Object.assign(front, rear)
                        return rear;
                    }
                    // 不是菜单就是按钮
                    this.menuState.button.push(rear.path)
                    return null;
                }).filter(item => item != null)
                this.menuState.menu = await interaction.flatToTree(list, 'id', 'parent', 'children')
            }catch(e ){
                console.log(e)
            }
        }
    },
    persist: [
        {
            key: 'BASE_STORE',
            pick: ['localState', 'menuFoldState', 'menuState'],
            storage: localStorage,
        },
        {
            key: 'BASE_STORE',
            pick: ['token','update','expired'],
            storage: sessionStorage,
        },
    ]
        // enabled: true,
        // strategies: [
        //     {
        //         key: 'BASE_STORE',
        //         storage: localStorage,
        //         paths: ['localState', 'token', 'menuFoldState', 'menuState','update','expired']
        //     }
        // ]
    // }
})
